package com.efrei.uchat.server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Observable;

import org.apache.log4j.Logger;

import com.efrei.uchat.utils.Const;

public class Server extends Observable implements Runnable {
	
	private static final Logger logger = Logger.getLogger(Server.class);
	
	public static int DEFAULT_PORT = Const.DEFAULT_PORT;
	
	private int port;
	private boolean active = true;

	private ServerSocket listener;
	
	public Server() {
		this.port = DEFAULT_PORT;
	}
	
	public Server(int port) {
		this.port = port;
	}
	
	@Override
	public void run() {
		try {
			listenClients();
		} catch(IOException e) {
			e.printStackTrace();
		}
	}
	
	private void listenClients() throws IOException {
		listener = new ServerSocket(port);
		Socket client;
		logger.info("Server listen on port "+port);
		
		while(active) {
			// wait clients
			client = listener.accept();
			logger.info("accepted client "+client);
			
			//notify observers
			setChanged();
			notifyObservers(client);
		}
	}
	
	public void close() {
		try {
			listener.close();
		} catch (IOException e) {
			logger.error("error while server shutdown", e);
		}
	}
}
